package com.example.broyue.music.data;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.example.broyue.music.R;
import com.example.broyue.music.model.PropertyBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity {

    //显示主键
    private ImageButton imgBtn_Previous;
    private ImageButton imgBtn_PlayOrPause;
    private ImageButton imgBtn_Stop;
    private ImageButton imgBtn_Next;
    private ListView list;

    //歌曲列表对象
    private ArrayList<Music> musicArrayList;

    //退出判断标记
    private static boolean isExit=false;
    //当前歌曲的序号，小标从0开始
    private int number;
    //播放状态
    private int status;
    //广播接收器
    private StatusChangedReceiver receiver;
    private RelativeLayout root_Layout;
    private TextView text_Current;
    private TextView text_Duration;
    private SeekBar seekBar;
    private TextView textView;
    private Handler seekBarHandler;

    //当前歌曲的持续时间和当前位置，作用于进度条
    private int duration;
    private int time;

    //进度条控制常量
    private static final int PROGRESS_INCREASE =0;
    private static final int PROGRESS_PAUSE =1;
    private static final int PROGRESS_RESET =2;

    //播放模式常量
    private static final int MODE_LIST_SEQUENCE=0;
    private static final int MODE_SINGLE_CYCLE=1;
    private static final int MODE_LIST_CYCLE=2;
    private int playmode;

    //音量控制
    private TextView tv_vel;
    private SeekBar seekBar_vel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViews();
        registerListener();
        initMusicList();
        initListView();
        checkMusicfile();
        duration=0;
        time=0;
        //绑定广播接收器，可以接收广播
        // binStatusChangeReceiver();
        initSeekBarHandler();
        startService(new Intent(this,MusicService.class));
        status=MusicService.COMMAND_STOP;
        //默认播放模式是顺序播放
        playmode=MainActivity.MODE_LIST_SEQUENCE;

    }

    //获取显示组件
    private  void findViews(){
        imgBtn_Previous = (ImageButton) findViewById(R.id.imageButton1);
        imgBtn_PlayOrPause = (ImageButton) findViewById(R.id.imageButton2);
        imgBtn_Stop = (ImageButton) findViewById(R.id.imageButton3);
        imgBtn_Next = (ImageButton) findViewById(R.id.imageButton4);
        list = (ListView) findViewById(R.id.listView1);
        seekBar= (SeekBar) findViewById(R.id.seekBar1);
        text_Current= (TextView) findViewById(R.id.textView1);
        text_Duration= (TextView) findViewById(R.id.textView2);
        root_Layout= (RelativeLayout) findViewById(R.id.relativeLayout1);
     /*   tv_vel= (TextView) findViewById(R.id.main_tv_volumeText);
        seekBar_vel= (SeekBar) findViewById(R.id.main_sb_volumebar);*/
    }

    //为显示组件注册监听事件
    private void registerListener(){
        imgBtn_Previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                moveNumberToPrvious();
                play(number);
                imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
            }
        });

        imgBtn_PlayOrPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(player != null && player.isPlaying()){
                    pause();
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                }else{
                    play(number);
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
                }
            }
        });

        imgBtn_Stop.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                stop();
                imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
            }
        });
        imgBtn_Next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                moveNumberToNext();
                play(number);
                imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
            }
        });
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                number = position ;
                play(number);
                imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(status != MusicService.STATUS_STOPPED){
                    time =seekBar.getProgress();
                    //更新文本
                    text_Current.setText(formatTime(time));
                    //发送广播给Musicservice,执行跳转
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                }
                if(status == MusicService.STATUS_PLAYING){
                    //发送广播给MusicService，执行跳转
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    //进度条恢复移动
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //进度条暂停移动
                seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
            }

            @Override
            public void onProgressChanged(SeekBar seekBar,int progess,boolean fromUser){}
        });

    }

    //初始化音乐对象
    private void initMusicList(){
        musicArrayList=MusicList.getMusicList();
        //避免重复添加音乐
        if (musicArrayList.isEmpty()){
            Cursor mMusicCursor=this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[] {MediaStore.Audio.Media.TITLE,
                            MediaStore.Audio.Media.DURATION,
                            MediaStore.Audio.Media.ALBUM,
                            MediaStore.Audio.Media._ID,
                            MediaStore.Audio.Media.DATA,
                            MediaStore.Audio.Media.DISPLAY_NAME},null,null ,
                    MediaStore.Audio.AudioColumns.TITLE);
            if (mMusicCursor!=null){
                //标题
                int indexTitle=mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
                //艺术家
                int indexArtist=mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
                //总时长
                int indexTotalTime=mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
                //路径
                int indexPath=mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);

                //通过mMusicCursor游标遍历数据库，并将Music类对象加载到ArrayList中
                for (mMusicCursor.moveToFirst();!mMusicCursor.isAfterLast();mMusicCursor.moveToNext()){
                    String strTitle=mMusicCursor.getString(indexTitle);
                    String strArtist=mMusicCursor.getString(indexArtist);
                    String strTotalTime=mMusicCursor.getString(indexTotalTime);
                    String strPath=mMusicCursor.getString(indexPath);

                    if (strArtist.equals("<unknown>")) {
                        strArtist = "无艺术家";
                    }
                    Music music=new Music(strTitle,strArtist,strPath,strTotalTime);
                    musicArrayList.add(music);
                }
            }
        }
    }

    //设置设配器并初始化listview
    private void initListView(){
        List<Map<String,String>> list_map=new ArrayList<Map<String,String>>();
        HashMap<String,String > map;
        SimpleAdapter simpleAdapter;
        for (Music music:musicArrayList){
            map=new HashMap<String,String>();
            map.put("musicName",music.getMusicName());
            map.put("musicArtist",music.getMusicArtist());
            list_map.add(map);
        }
        String [] from=new String[]{"musicName","musicArtist"};
        int [] to={R.id.listview_tv_title_item,R.id.listview_tv_artist_item};

        simpleAdapter=new SimpleAdapter(this,list_map,R.layout.listview,from,to);
        list.setAdapter(simpleAdapter);
    }

    //如果列表没有歌曲，则播放按钮不可用，并提醒客户
    private void checkMusicfile(){
        if (musicArrayList.isEmpty()){
            imgBtn_Next.setEnabled(false);
            imgBtn_PlayOrPause.setEnabled(false);
            imgBtn_Previous.setEnabled(false);
            imgBtn_Stop.setEnabled(false);
            Toast.makeText(getApplicationContext(),"当前没有歌曲文件",Toast.LENGTH_SHORT).show();
        }else{
            imgBtn_Stop.setEnabled(true);
            imgBtn_Next.setEnabled(true);
            imgBtn_Previous.setEnabled(true);
            imgBtn_PlayOrPause.setEnabled(true);
        }
    }

    @Override
    protected void onResume(){
        super.onResume();
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
        PropertyBean property=new PropertyBean(MainActivity.this);
        String theme=property.getTheme();
        setTheme(theme);
        audio_Control();
    }
    private String formatTime(int msec) {
        int minute = msec / 1000 / 60;
        int second = msec / 1000 % 60;
        String minuteString;
        String secondString;
        if (minute < 10) {
            minuteString = "0" + minute;
        } else {
            minuteString = "" + minute;
        }
        if (second < 10) {
            secondString = "0" + second;
        } else {
            secondString = "" + second;
        }
        return minuteString + ":" + secondString;
    }

    /**
     * 发送命令，控制音乐播放。参数定义在MusicService类中
     */
    private void sendBroadcastOnCommand(int command) {

        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        //根据不同命令，封装不同的数据
        switch (command) {
            case MusicService.COMMAND_PLAY:
                intent.putExtra("number", number);
                break;
            case MusicService.COMMAND_SEEK_TO:
                intent.putExtra("time",time);
                break;
            case MusicService.COMMAND_PREVIOUS:
            case MusicService.COMMAND_NEXT:
            case MusicService.COMMAND_PAUSE:
            case MusicService.COMMAND_STOP:
            case MusicService.COMMAND_RESUME:
            default:
                break;
        }
        sendBroadcast(intent);
    }


    /**
     * 内部类，用于播放器状态更新的接收广播
     */
    class StatusChangedReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            //获取播放器状态
            status = intent.getIntExtra("status", -1);
            switch (status) {
                case MusicService.STATUS_PLAYING:
                    String musicName = intent.getStringExtra("musicName");
                    String musicArtist = intent.getStringExtra("musicAritist");
                    seekBarHandler.removeMessages(PROGRESS_INCREASE);
                    time = intent.getIntExtra("time", 0);
                    duration = intent.getIntExtra("duration", 0);
                    number = intent.getIntExtra("number", number);
                    list.setSelection(number);
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                    text_Duration.setText(formatTime(duration));
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.pause);
                    //设置textview文字，提示已经播放的歌曲
                    MainActivity.this.setTitle("正在播放:" + musicName + " - " + musicArtist);
                    break;
                case MusicService.STATUS_PAUSED:
                    seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    String string = MainActivity.this.getTitle().toString().replace("正在播放", "已暂停");
                    MainActivity.this.setTitle(string);
                case MusicService.STATUS_STOPPED:
                    time = 0;
                    duration = 0;
                    text_Current.setText(formatTime(time));
                    text_Duration.setText(formatTime(duration));
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle("GracePlayer");
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                case MusicService.STATUS_COMPLETED:
                    number = intent.getIntExtra("number", 0);
                    if(playmode == MainActivity.MODE_LIST_SEQUENCE)//顺序播放
                    {
                        if (number == MusicList.getMusicList().size() - 1)
                            sendBroadcastOnCommand(MusicService.STATUS_STOPPED);
                        else
                            sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                    }
                    else if(playmode == MainActivity.MODE_SINGLE_CYCLE)
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);//单曲播放
                    else if(playmode == MainActivity.MODE_LIST_CYCLE)//列表循环
                    {
                        if (number == MusicList.getMusicList().size() - 1)
                        {
                            number =0;
                            sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        }else sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                    }
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle("");
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if (status == MusicService.STATUS_STOPPED) {
            stopService(new Intent(this, MusicService.class));
        }
        super.onDestroy();
    }

    //设置Activity的主题，包括修改背景图片等等
    private void setTheme(String theme) {
        if ("彩色".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.drawable.bg_color);
        } else if ("花朵".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.drawable.bg_digit_flower);
        } else if ("群山".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.drawable.bg_mountain);
        } else if ("小狗".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.drawable.bg_running_dog);
        } else if ("冰雪".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.drawable.bg_snow);
        } else if ("女孩".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.drawable.bg_music_girl);
        } else if ("朦胧".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.drawable.bg_blur);
        }
    }

    /*创建菜单*/
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /*处理菜单点击事件*/
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            //显示列表对话框
            case R.id.menu_theme:
                (new AlertDialog.Builder(this)).setTitle("请选择主题").setItems(R.array.theme, new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String theme = PropertyBean.THEMES[which];
                        MainActivity.this.setTheme(theme);
                        PropertyBean property = new PropertyBean(MainActivity.this);
                        property.setAndSaveTheme(theme);
                    }
                }).show();
                break;
            case R.id.menu_about:
                //显示文本对话框
                (new AlertDialog.Builder(this)).setTitle("GracePlayer").setMessage(R.string.about2).show();
                break;
            case R.id.menu_quit:
                //退出程序
                (new AlertDialog.Builder(this)).setTitle("提示").setMessage(R.string.quit).setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        System.exit(0);
                    }
                }).setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                }).show();
                break;
            case R.id.menu_playmode:
                String[] mode = new String[]{"顺序播放", "单曲循环", "列表循环"};
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("播放模式");
                builder.setSingleChoiceItems(mode, playmode,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                playmode = which;
                            }
                        });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (playmode) {
                            case 0:
                                playmode = MainActivity.MODE_LIST_SEQUENCE;
                                Toast.makeText(getApplicationContext(), R.string.sequence, Toast.LENGTH_SHORT).show();
                                break;
                            case 1:
                                playmode = MainActivity.MODE_SINGLE_CYCLE;
                                Toast.makeText(getApplicationContext(), R.string.singlecycle, Toast.LENGTH_SHORT).show();
                                ;
                                break;
                            case 2:
                                playmode = MainActivity.MODE_LIST_CYCLE;
                                Toast.makeText(getApplicationContext(), R.string.listcycle, Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                });
                builder.create().show();
        }
        return super.onOptionsItemSelected(item);
    }

    //按键响应
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int progress;
        switch (keyCode){
            case KeyEvent.KEYCODE_BACK:
                exitByDoubleClick();
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                progress=seekBar_vel.getProgress();
                if (progress !=0)
                    seekBar_vel.setProgress(progress-1);
                return true;
            case KeyEvent.KEYCODE_VOLUME_UP:
                progress=seekBar_vel.getProgress();
                if (progress!=seekBar_vel.getMax())
                    seekBar_vel.setProgress(progress+1);
                return true;
            default:
                break;
        }
        return false;
    }

    //双击返回后退出
    private void exitByDoubleClick(){
        Timer timer=null;
        if (isExit==false){
            isExit=true;
            Toast.makeText(this,"再按一次退出程序",Toast.LENGTH_SHORT).show();
            timer=new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit=false;
                }
            },2000);//两秒后会执行run函数的内容，如果两秒内没按下返回键，则定时器修改isExit的值
        }else{
            System.exit(0);
        }
    }

    private void initSeekBarHandler() {
        seekBarHandler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case PROGRESS_INCREASE:
                        if (seekBar.getProgress() < duration) {
                            //进度条前进一秒
                            seekBar.setProgress(time);
                            seekBar.incrementProgressBy(1000);
                            seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            //修改显示当前进度的文本
                            text_Current.setText(formatTime(time));
                            time += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        //重置进度条画面
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        text_Current.setText("00:00");
                        break;
                }
            }
        };
    }

    //媒体播放器
    private MediaPlayer player=new MediaPlayer();

    //读取音乐文件
    private void load(int number){
        try{
            player.reset();
            player.setDataSource(MusicList.getMusicList().get(number).getMusicPath());
            player.prepare();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //播放音乐
    private void play(int number){
        //停止当前播放
        if (player!=null && player.isPlaying()){
            player.stop();
        }
        load(number);
        player.start();
    }

    //暂停音乐
    private void pause(){
        if (player.isPlaying()){
            player.pause();
        }
    }

    //停止播放
    private void stop(){
        player.stop();
    }

    //恢复播放（暂停之后）
    private void resume(){
        player.start();
    }

    //重新播放（播放完成之后）
    private void replay(){
        player.start();
    }

    //选择下一曲
    private void moveNumberToNext(){
        //判断是否到达列表底端
        if ((number)==MusicList.getMusicList().size()-1){
            Toast.makeText(MainActivity.this,MainActivity.this.getString(R.string.tip_reach_bottom),Toast.LENGTH_SHORT).show();
        }else{
            ++number;
            play(number);
        }
    }

    //选择上一曲
    private void moveNumberToPrvious(){
        //判断是否到达列表顶端
        if (number==0){
            Toast.makeText(MainActivity.this,MainActivity.this.getString(R.string.tip_reach_top),Toast.LENGTH_SHORT).show();
        }else{
            --number;
            play(number);
        }
    }

    //音量的控制
    private void audio_Control(){
        //获得音量管理器
        final AudioManager audioManager= (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        //设置当前调整音量大小只是针对媒体音乐
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        //设置滑动条的最大值
        final int max_pregress=audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        seekBar_vel.setMax(max_pregress);
        //获取当前音量
        int progress=audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        seekBar_vel.setProgress(progress);
        tv_vel.setText("音量： "+(progress*100/max_pregress)+"%");
        seekBar_vel.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tv_vel.setText("音量： "+(progress*100/max_pregress)+"%");
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,progress,AudioManager.FLAG_PLAY_SOUND);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }


}
